<template>
  <div class="map">
    <el-select v-model="formData.province" value-key="id" filterable remote reserve-keyword remote-show-suffix>
      <el-option v-for="item in regions" :key="item.id" :label="item.name" :value="item" />
    </el-select>
    <el-select v-model="formData.city" value-key="id" filterable remote reserve-keyword remote-show-suffix>
      <el-option v-for="item in formData.province.children" :key="item.adcode" :label="item.name" :value="item" />
    </el-select>
    <el-select v-model="formData.district" value-key="id" filterable remote reserve-keyword remote-show-suffix>
      <el-option v-for="item in formData.city.children" :key="item.id" :label="item.name" :value="item" />
    </el-select>
  </div>
</template>
<script lang="ts" setup name="Amap">
import { ref, reactive, onBeforeMount, watch } from "vue";
import region from "./region.json";

const props = defineProps({
  modelValue: {
    type: Number
  }
});

const formData = reactive({
  province: "",
  city: "",
  district: ""
});

const emits = defineEmits(["update:modelValue"]);
watch(
  () => formData.district,
  newValue => {
    emits("update:modelValue", newValue.id);
  }
);

watch(formData, newValue => {
  if (!newValue.province) {
    formData.city = "";
    formData.district = "";
  } else if (!newValue.city || newValue.city.parent_id != newValue.province.id) {
    formData.city = "";
    formData.district = "";
  } else if (newValue.district.parent_id != newValue.city.id) {
    formData.district = "";
  }
});

const regions = ref(region[0].children);
const init = () => {
  if (props.modelValue) {
    regions.value.forEach(province => {
      province.children.forEach(city => {
        city.children.forEach(district => {
          if (district.id == props.modelValue) {
            formData.province = province;
            formData.city = city;
            formData.district = district;
            return;
          }
        });
      });
    });
  }

  formData.address = props.address;
};

onBeforeMount(init);
watch(
  () => props.modelValue,
  newValue => {
    props.modelValue = newValue;
    init();
  }
);
</script>
<style scoped>
.map {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
  width: 100%;
  padding: 0 2px;
  margin-bottom: 5px;
}
</style>
